from settings import URL,DOWN_DIR
from settings import mkdir,jb
from alist_api import fs_list,login
from aria2down import pikpak_down
from urllib.parse import quote,unquote
from mylog import LOG
logger = LOG('日志.txt',text='\n--------------运行---------------------')
log = logger.log


'''
开启alist服务

开启aria2rpc服务

'''
token = login()
deep_path = ''
# deep_path
def down(url = URL,download_dir =DOWN_DIR):
    global deep_path,token
    if '?sign' in url:
        # 是文件
        fname = unquote(jb(url, '/', '?'))
        log("下载文件:",fname)
        pikpak_down(url, fname)
    else:
        # 是目录
        fs_tree = fs_list(url,token)
        if not fs_tree['message']=='success':
            if fs_tree['code'] == '401':
                fs_tree = fs_list(url,login())
                log('更新token')
            else:
                log("Error:\n",fs_tree)
        assert fs_tree['message'] == 'success'
        # create last dir
        deep_path += unquote(url.split('/')[-1]) + '/'
        mkdir(deep_path)
        log("deepin_path: ",deep_path)
        # kong dir
        if fs_tree['data']['total'] == 0:
            log('kong dir: ',deep_path)
            return
        # download file
        a,b,c,d= url.split('/',maxsplit=3)
        durl = a + r'//' + c + '/d/'+ d
            # 解析json树,xian file,hou dir.
        for f in fs_tree['data']['content']:
            if not f['is_dir']:
                log("下载文件:",f['name'])
                pikpak_down(url= durl + "/" + quote(f['name']) + "?sign=" + f['sign'], 
                            fname= f['name'], 
                            dir= DOWN_DIR + '/' + deep_path)
        for f in fs_tree['data']['content']:
            if f['is_dir']:
                # 1.新建文件夹
                mkdir(deep_path + f['name'])
                # 2.递归下载
                _deep_path = deep_path
                down(url= url + '/' + quote(f['name']),download_dir = deep_path+f['name'])
                deep_path = _deep_path
    log('---------------------------------finish')






if __name__ == '__main__':
    down()
